package com.xiaoc.bulldozer.service.impl;

import com.google.gson.JsonObject;
import com.xc.framework.cache.manager.CacheManager;
import com.xc.framework.cache.utils.CacheUtils;
import com.xc.framework.common.utils.HttpUtil;
import com.xiaoc.bulldozer.common.CacheKeys;
import com.xiaoc.bulldozer.common.Constant;
import com.xiaoc.bulldozer.common.WeixinConstant;
import com.xiaoc.bulldozer.service.WxService;
import org.apache.commons.lang.StringUtils;
import org.apache.http.impl.client.CloseableHttpClient;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.LinkedHashMap;
import java.util.Map;

@Service("wxService")
public class WxServiceImpl implements WxService {

    private static final Logger logger = LoggerFactory.getLogger(WxServiceImpl.class);

    @Value("${wechat.miniapp.appid}")
    private String appId;
    @Value("${wechat.miniapp.secret}")
    private String appSecret;

    @Resource
    private CloseableHttpClient closeableHttpClient;

    @Resource(name = "remoteCacheManager")
    private CacheManager remoteCacheManager;

    @Override
    public String getAccessToken() {

        String accessToken = (String) remoteCacheManager.get(CacheUtils.generateCacheKey(CacheKeys.WX_ACCESS_TOKEN));

        if (StringUtils.isNotEmpty(accessToken)) {
            return accessToken;
        }

        Map<String, Object> params = new LinkedHashMap<String, Object>();
        params.put("grant_type", "client_credential");
        params.put("appid", appId);
        params.put("secret", appSecret);

        JsonObject json = HttpUtil.getSimpleRequestJson(closeableHttpClient, WeixinConstant.WX_ACCESS_TOKEN_URL, params);

        accessToken = json.get("access_token").getAsString();

        remoteCacheManager.put(CacheUtils.generateCacheKey(CacheKeys.WX_ACCESS_TOKEN), accessToken, Constant.ACCESS_TOKEN_SESSION_TIMEOUT);

        return accessToken;
    }
}
